package com.konjac.service.impl;

import com.konjac.dao.mapper.AddOrderMapper;
import com.konjac.dao.mapper.SaleOrderMapper;
import com.konjac.dao.mapper.ShowBookMapper;
import com.konjac.pojo.BookInfo;
import com.konjac.pojo.SaleOrder;
import com.konjac.pojo.ServiceState;
import com.konjac.service.SaleOrderService;
import com.konjac.until.Handle;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SaleOrderServiceImpl implements SaleOrderService {
//销售:输入顾客要买书籍的信息，自动显示此书的库存量，如果可以销售，打印销售单并修改库存，同时把此次销售的有关信息添加到日销售表中
    public ServiceState sale(String bookId, String username, Integer saleNumber) throws IOException {
        //加载mybaits核心配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        SaleOrderMapper saleOrderMapper = sqlSession.getMapper(SaleOrderMapper.class);
        ShowBookMapper showBookMapper = sqlSession.getMapper(ShowBookMapper.class);

        //加载实体类
        BookInfo bookInfo = null;
        SaleOrder saleOrder = new SaleOrder();
        saleOrder.setUsername(username);
        saleOrder.setBookId(bookId);
        saleOrder.setSaleNumber(saleNumber);
        ServiceState serviceState = new ServiceState();
        bookInfo = showBookMapper.selectAllByBookId(bookId);

        if (saleNumber > bookInfo.getBookQty()) {
            serviceState.setFlag(0);
            serviceState.setMsg("库存不足,请重新选择书籍的数量!!!");
            System.out.println(serviceState.getMsg());
            return serviceState;
        }
        if (saleNumber < 1) {
            serviceState.setFlag(0);
            serviceState.setMsg("至少购买一本!!!");
            System.out.println(serviceState.getMsg());
            return serviceState;
        }
        //填充订单数据
        saleOrder.setSalePrice(saleNumber * bookInfo.getBookPrice());
        saleOrder.setSaleTime(Handle.getDateAndTime());


        try {
            //提交订单信息并修改库存
            saleOrderMapper.addOrder(saleOrder);
            bookInfo.setBookQty(bookInfo.getBookQty() - saleNumber);
            showBookMapper.updateBookInfo(bookInfo);
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
            serviceState.setMsg("销售订单提交时出错!!!");
            serviceState.setFlag(0);
            //System.out.println(serviceState.getMsg());
            return serviceState;
        } finally {
        }

        //提交事件
        sqlSession.commit();
        sqlSession.close();
        return serviceState;
    }
}
